﻿using DLC.Game.DataTable;
using DLC.Module.DataTable;
using DLC.Module.DataTable.ArchiveBytes;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;

namespace DLC.Example.Bytes
{
	public class LoadDataTables : MonoBehaviour
	{
		public readonly IDataTableManager DataTableManager = new DataTableManager();

		public List<AssetReference> DataTableAssetRefs;
		[SerializeField]
		public Dictionary<string, AssetReference> DataTableAssetTypeRefs;

		void Start()
		{
			foreach (var dataAR in DataTableAssetRefs)
			{
				dataAR.LoadAssetAsync<TextAsset>().Completed += OnDataTableLoaded;
			}
		}

		AssetReference GetAssetReference(AsyncOperationHandle<TextAsset> obj)
		{
			foreach (var dataAR in DataTableAssetRefs)
			{
				if (dataAR.OperationHandle.Equals(obj))
				{
					return dataAR;
				}
			}
			return null;
		}

		private void OnDataTableLoaded(AsyncOperationHandle<TextAsset> obj)
		{
			Debug.Log($"OnDataTableLoaded......{obj.Result.GetType()}");
			var da = GetAssetReference(obj);
			Debug.Log($"Asset.name......{da.Asset.name}");
			var ss = da.Asset.name.Split('_');

			DataTableManager.CreateDataTable(ss[0], obj.Result.bytes);

			//DataTableManager.AddDataTable(da.Asset.name, t);

			var table = DataTableManager.GetDataTable<ExcelExampleTempData>(ss[0]);
            if (table != null)
            {
				Debug.Log($"Get Data Table table is {table}..{table.GetDataRow(1).Name}..{table.Count}");
			}

            var tables = DataTableManager.GetDataTables(ss[0]);
            foreach (var tt in tables)
            {
				Debug.Log($"Get Data Table table is {table}.");
			}
        }
	}
}